﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Project_1.Models;
using System.Data;
using System.Web.Helpers;

namespace Project_1.Controllers
{
    public class UserController : Controller
    {
        private const string connectionString = "Data Source=(local);Initial Catalog=AnsBook;Integrated Security=SSPI";
        AnsBookContext db = new AnsBookContext(connectionString);

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model)
        {
            if (ModelState.IsValid)
            {
                User theUser = db.Users.Find(model.UserName);
                if (theUser != null && theUser.Password.Equals(model.Password))
                {
                    Session["Username"] = model.UserName;
                    if (model.RememberMe == true)
                    {
                        var userCookie = new HttpCookie("userCookie");
                        userCookie["Username"] = model.UserName;
                        userCookie["Password"] = model.Password;
                        Response.Cookies.Add(userCookie);
                    }
                    return TempData["Action"] != null ? RedirectToAction(TempData["Action"].ToString(), TempData["Controller"].ToString()) : RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("1", "The username - password match is not correct");
                    return View(model);
                }
            }
            return View(model);
        }

        public ActionResult LogOff()
        {
            if (Request.Cookies["userCookie"] != null)
            {
                HttpCookie userCookie = new HttpCookie("userCookie") { Expires = DateTime.Now.AddDays(-1d) };
                Response.Cookies.Add(userCookie);
            }
            Session["Username"] = null;
            return RedirectToAction("Index", "Home");
        }

        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                User newUser = new User();
                newUser.Username = model.UserName;
                newUser.Password = model.Password;
                newUser.Type = 1;
                newUser.CreateTime = DateTime.Now;
                newUser.LastVisit = newUser.CreateTime;
                newUser.Point = 0;
                newUser.Avatar = false;
                newUser.Email = model.Email;
                newUser.Birthday = newUser.CreateTime;
                newUser.CommentViewStyle = 1;
                newUser.ListViewStyle = 1;
                newUser.AllowInfoView = true;
                //try
                //{
                    db.Entry(newUser).State = EntityState.Added;
                    db.SaveChanges();
                //}
                //catch
                //{

                //}
                Session["Username"] = model.UserName;
                return RedirectToAction("Index", "Home");
            }
            return View(model);
        }

        public ActionResult ChangePassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                User theUser = db.Users.Find(Session["Username"]);
                if (theUser.Password.Equals(model.OldPassword))
                {
                    theUser.Password = model.NewPassword;
                }
                db.Entry(theUser).State = EntityState.Modified;
                db.SaveChanges();
                return View(model);
            }
            return View(model);
        }

        public ActionResult ChangeInformation()
        {
            ChangeInformationModel model = new ChangeInformationModel();
            User theUser = db.Users.Find(Session["Username"]);
            model.AboutMe = theUser.AboutMe;
            model.AllowInfoView = theUser.AllowInfoView;
            model.Avatar = theUser.Avatar;
            model.Birthday = theUser.Birthday;
            model.CommentViewStyle = model.CommentViewStyle;
            model.Email = theUser.Email;
            model.Gender = theUser.Gender;
            model.HomePage = theUser.HomePage;
            model.ListViewStyle = theUser.ListViewStyle;
            model.Location = theUser.Location;
            model.Phone = theUser.Phone;
            model.RealName = theUser.RealName;
            model.SubcribeUsers = theUser.SubcribeUsers;
            return View(model);
        }

        [HttpPost]
        public ActionResult ChangeInformation(ChangeInformationModel model)
        {
            if (ModelState.IsValid)
            {
                User theUser = db.Users.Find(Session["Username"]);
                theUser.AboutMe = model.AboutMe;
                theUser.AllowInfoView = model.AllowInfoView;
                theUser.Avatar = model.Avatar;
                theUser.Birthday = model.Birthday;
                theUser.CommentViewStyle = model.CommentViewStyle;
                theUser.Email = model.Email;
                theUser.Gender = model.Gender;
                theUser.HomePage = model.HomePage;
                theUser.ListViewStyle = model.ListViewStyle;
                theUser.Location = model.Location;
                theUser.Phone = model.Phone;
                theUser.RealName = model.RealName;
                theUser.SubcribeUsers = model.SubcribeUsers;
                db.Entry(theUser).State = EntityState.Modified;
                db.SaveChanges();
                return View(model);
            }
            return View(model);
        }

        public ActionResult ViewInformation(string username)
        {
            User theUser = db.Users.Find(username);
            if (theUser != null)
            {
                if (theUser.AllowInfoView == true)
                {
                    ViewBag.Infor = theUser;
                }
                else
                {
                    ViewBag.Message = "The user do not allow you to view his/her information";
                }
            }
            else
            {
                ViewBag.Message = "The username is not correct!";
            }
            return View();
        }

        public static void GetDefaultAvatar()
        {
            WebImage wbImage = new WebImage("~/Images/user-large.png");
            wbImage.Resize(300, 300);
            wbImage.FileName = "user-large.png";
            wbImage.Write();
        }

        public static void GetAvatar(string username)
        {
            WebImage wbImage = new WebImage(String.Format("~/Images/{0}.png", username));
            wbImage.Resize(300, 300);
            wbImage.FileName = username + ".png";
            wbImage.Write();
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
